/* Error handling: Takes a message, outputs it and closes the application. */

#include <allegro.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "main.h"

/* Requires Allegro to be initialized. Does not return. */
/* Syntax is a bit like printf:
 * bailout ("sdsd", "Player position: ", x, "/", y)
 * format parameter contains [printf format specifiers without %] and nothing else.
 * e.g. "sdsd" for string - int - string - int
 */
void bailout (char* format, ...)
{
	fprintf (stderr, "BAILOUT!\n");
	
	va_list ap;
	char* c;
	char wholemessage[256] = "Error: ";
	char* writeptr = wholemessage + strlen(wholemessage);
	int e = errno;
	
	/*
	if (set_gfx_mode(GFX_SAFE, 640, 480, 0, 0) != 0) {
		exit (1); // no error message output 
	}
	*/

	va_start(ap, format); 
	for (c = format; *c != '\0'; c++) {
		switch (*c) {
			case 's':
				sprintf (writeptr, "%s", va_arg(ap, const char*));
				break;
			
			case 'd':
				sprintf (writeptr, "%d", va_arg(ap, int));
				break;
			
			default:
				sprintf (writeptr, "[unknown arg %c]", *c);
				break;
		}
		writeptr += strlen(writeptr);
	}
	va_end(ap);
	
		#if TOWERHACK_DEBUG
		fprintf (stderr, "[Debug] Error: %s\n\terrno = %d\n", wholemessage, e);
		#endif
		
	char errno_str [50];
	sprintf (errno_str, "errno = %d", e);
		
	while (!key[KEY_ESC]) {
		textout_centre_ex(screen, font, wholemessage, SCREEN_W/2, SCREEN_H/2, makecol (255, 0, 0), makecol(0,0,0));
		textout_centre_ex(screen, font, errno_str, SCREEN_W/2, SCREEN_H/2 +20, makecol (255, 0, 0), makecol(0,0,0));
	}

	exit (1);
}
